package ntancnit.app.firebase;

import ntancnit.app.database.GetUserName;
import ntancnit.app.whereareyou.DialogAlert;
import ntancnit.app.whereareyou.FriendActivity;
import ntancnit.app.whereareyou.MainActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
import android.util.Log;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;

public class FireBase {

	public static void sendToServer(String content) {
		Firebase ref = new Firebase("https://burning-fire-8831.firebaseio.com/");
		ref.setValue(content);
	}

	public static void listentService(final Context context) {
		Firebase ref = new Firebase("https://burning-fire-8831.firebaseio.com/");
		ref.addValueEventListener(new ValueEventListener() {

			@Override
			public void onDataChange(DataSnapshot snap) {
				System.out.println(snap.getName() + " -> " + snap.getValue());
				Log.w("#########", "##########" + snap.getValue());
				GetUserName userName = new GetUserName(context);
				String[] str = snap.getValue().toString().split("######");
				if (str.length == 5) {
					if (userName.getUserName().equals(str[1])) {
						Intent intent = new Intent(context, DialogAlert.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("lat", str[3]);
						intent.putExtra("lng", str[4]);
						intent.putExtra("content", str[2]);
						intent.putExtra("name", str[0]);
						context.startActivity(intent);

						Vibrator vibrator = (Vibrator) context
								.getSystemService(Context.VIBRATOR_SERVICE);
						vibrator.vibrate(2000);

						Uri notification = RingtoneManager
								.getDefaultUri(RingtoneManager.TYPE_ALARM);
						MediaPlayer mp = MediaPlayer.create(
								context.getApplicationContext(), notification);
						mp.start();
					}
				}
			}

			@Override
			public void onCancelled(FirebaseError error) {
			}
		});
	}
}
